package comtgl.demo.utils;

//import com.kingdee.eas.eclite.ui.utils.Base64;

import org.springframework.security.crypto.codec.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    static final String algorithmStr = "AES/CBC/PKCS5Padding";
    //注意: 这里的password(秘钥必须是16位的)
    private static final String keyBytes = "5ssHaSRfvbMygcfT";

    private static final String ivBytes = "9cROn9IcKZI5ySpA";


    private static byte[] encrypt(String content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            IvParameterSpec iv = new IvParameterSpec(ivBytes.getBytes());
            Cipher cipher = Cipher.getInstance(algorithmStr);//algorithmStr
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key,iv);//   ʼ
            byte[] result = cipher.doFinal(byteContent);
            return result; //
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] decrypt(byte[] content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            IvParameterSpec iv = new IvParameterSpec(ivBytes.getBytes());
            Cipher cipher = Cipher.getInstance(algorithmStr);//algorithmStr
            cipher.init(Cipher.DECRYPT_MODE, key,iv);//   ʼ
            byte[] result = cipher.doFinal(content);
            return result; //
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] getKey(String password) {
        byte[] rByte = null;
        if (password!=null) {
            rByte = password.getBytes();
        }else{
            rByte = new byte[24];
        }
        return rByte;
    }

    /**
     *加密
     */
    public static String encode(String content){
        //加密之后的字节数组,转成16进制的字符串形式输出
        return new String(Base64.encode(encrypt(content, keyBytes)));
    }

    /**
     *解密
     */
//    public static String decode(String content){
//        //解密之前,先将输入的字符串按照16进制转成二进制的字节数组,作为待解密的内容输入
//        byte[] b = decrypt(Base64.decode(content), keyBytes);
//        return new String(b);
//    }

}